package com.authine.cloudpivot.ext.controller;


import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
/**
 * 意见记录
 */
@Slf4j
@RestController
@RequestMapping("/public/suggestRecord")
public class suggestRecord extends BaseController {


    @Autowired
    CloudSqlService sqlService;

    /**
     * 意见记录  审批流完成后 数据写到-意见记录 基础表 基础
     */
    @RequestMapping("finish")
    public void finish(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.suggestrecord, bizId);

        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("Sheet1720078852936");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        //获取审批人

        String approval = getFileBaseInfoWorkFlowApproval(bizObject);

        for (Map<String, Object> map : list) {

            try {
                //获取数据
                Map<String, Object> data = fileInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(map);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.OpinionRecordBase, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-人员信息基础作成功 ");
                //调用存储过程
                callProcess(id);

            } catch (Exception e) {
                String txtMainDeptCode = (String) map.get("txtMainDeptHide");
                String txtPersonCode = (String) map.get("txtPersonCode");
                log.info("基础表-意见表准信息基础操作失败 txtMainDeptCode={},txtPersonCode={}", txtMainDeptCode, txtPersonCode);
                log.info(e.getMessage(), e);
            }

        }
    }

    @RequestMapping("toVoid")
    public void toVoid(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.OpinionRecordVoid, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("SheetOpinionVoid");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        //获取审批人

        String approval = getFileBaseInfoWorkFlowApproval(bizObject);

        for (Map<String, Object> map : list) {


            try {
                //获取数据
                Map<String, Object> data = fileInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(data);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.OpinionRecordBase, data, false);
                model.setSequenceStatus(SequenceStatus.CANCELED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-人员信息基础作废操作成功 ");
                //调用存储过程
                callProcessToVoid(id);

            } catch (Exception e) {
                String txtMainDeptCode = (String) map.get("DeptCodeHide");
                String txtPersonCode = (String) map.get("txtPersonCode");

                log.info("基础表-意见表 作废信息基础操作失败 txtMainDeptCode={},txtPersonCode={}", txtMainDeptCode, txtPersonCode);
                log.info(e.getMessage(), e);
            }

        }
    }


    /**
     * 调用存储过程
     create  proc    SyncOpinion        ------意见表 新增
     (
     @ComCode   nvarchar(10),    ----公司代码
     @DeptCode    nvarchar(10),    ----部门代码
     @PersonCode   nvarchar(10),   ----人员代码
     @MainDeptCode    nvarchar(10),    ----责任部门代码
     @submitdate  nvarchar(50),		----提出日期
     @txtDesc   nvarchar(255),		----说明
     @auditdate  nvarchar(50)		----审批时间
     )
     */
    private void callProcess(String bizId) {

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.OpinionRecordBase);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                //.append("' and oneLevelCode='").append(oneLevelCode)
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}", map);

        //调用存储过程
        String txtComCode = MapUtils.getString(map, "txtComCode", "");
        String txtdeptCode = MapUtils.getString(map, "txtdeptCode", "");
        String txtPersonCode = MapUtils.getString(map, "txtPersonCode", "");
        String txtMainDeptCode = MapUtils.getString(map, "txtMainDeptCode", "");
        LocalDateTime SubmitDateTemp = (LocalDateTime) map.get("SubmitDate");
        String SubmitDate =  ObjectUtils.isEmpty(SubmitDateTemp) ? "" : SubmitDateTemp.toLocalDate().toString();
        String txtDesc = MapUtils.getString(map, "txtDesc", "");

        String auditDate = MapUtils.getString(map,"auditDate","");

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncOpinion   '%s','%s','%s','%s','%s','%s','%s'",
                txtComCode, txtdeptCode, txtPersonCode, txtMainDeptCode, SubmitDate, txtDesc, auditDate);

        log.info("\n==========准备调用存储过程:{}", execSql);

        sqlService.execute(CloudSqlService.htEas, execSql);

        log.info("\n=============存储过程执行完成");

    }

    /**
     * 调用作废存储过程
     create  proc    OpinionVoid        ------意见表 作废
     (
     @ComCode   nvarchar(10),    ----公司代码
     @DeptCode    nvarchar(10),    ----部门代码
     @PersonCode   nvarchar(10),   ----人员代码
     @MainDeptCode    nvarchar(10),    ----责任部门代码
     @submitdate  nvarchar(50),		----提出日期
     @txtDesc   nvarchar(255),		----说明
     @auditdate  nvarchar(50)		----审批时间
     )
     */
    private void callProcessToVoid(String bizId) {

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.OpinionRecordBase);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}", map);
        //调用存储过程
        String txtComCode = MapUtils.getString(map, "txtComCode", "");
        String txtdeptCode = MapUtils.getString(map, "txtdeptCode", "");
        String txtPersonCode = MapUtils.getString(map, "txtPersonCode", "");
        String txtMainDeptCode = MapUtils.getString(map, "txtMainDeptCode", "");
        LocalDateTime SubmitDateTemp = (LocalDateTime) map.get("SubmitDate");
        String SubmitDate =  ObjectUtils.isEmpty(SubmitDateTemp) ? "" : SubmitDateTemp.toLocalDate().toString();
        String txtDesc = MapUtils.getString(map, "txtDesc", "");

        String auditDate = MapUtils.getString(map,"auditDate","");


        String execSql = String.format("exec [HG_LINK].[hg].[dbo].OpinionVoid '%s','%s','%s','%s','%s','%s','%s'",
                txtComCode, txtdeptCode,txtPersonCode ,txtMainDeptCode,SubmitDate , txtDesc ,auditDate);

        log.info("\n==========准备调用作废存储过程:{}", execSql);

        sqlService.execute(CloudSqlService.htEas, execSql);

        log.info("\n=============作废存储过程执行完成");

    }

    /**
     * 查询审批人,返回  员工号+姓名
     *
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject) {


        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = "Activity11";
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append("　").append(user.getName()).toString();
    }


    /**
     * 判断是否已存在
     *
     * @return
     */
    private String existsBizObject(Map data) {

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.OpinionRecordBase);
        String txtMainDeptCode = (String) data.get("txtMainDeptCode");
        String txtDesc = (String) data.get("txtDesc");

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where txtMainDeptCode='").append(txtMainDeptCode)
                .append("' and txtDesc='").append(txtDesc)
                .append("';");

        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     * 转换成  基础表-意见表 的数据
     *
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String, Object> fileInfoBaseMap(Map<String, Object> map, String auditDate, String auditer) {
        Map<String, Object> data = new HashMap<>();


        //公司代码
        data.put("txtComCode", map.get("txtcomcodehide"));
        //部门代碼
        data.put("txtdeptCode", map.get("txtdeptCodeHide"));

        //部门
        data.put("txtDept", map.get("txtDept"));
        //意见人代码
        data.put("txtPersonCode", map.get("txtPersonCode"));
        //意见人
        data.put("txtPerson", map.get("txtPerson"));

        //责任部门代码
        data.put("txtMainDeptCode", map.get("txtMainDeptHide"));
        //责任部门
        data.put("txtMainDept", map.get("txtDutyDept"));
        //提出日期
        data.put("SubmitDate", map.get("DateSubmit"));

        //说明
        data.put("txtDesc", map.get("txtDesc"));
                //审批时间
        data.put("auditDate", auditDate);
        //审批人
        data.put("auditer", auditer);

        return data;
    }
}
